package cn.kgc.boot.vue.controller;

import cn.hutool.crypto.SecureUtil;
import cn.kgc.boot.vue.entity.User;
import cn.kgc.boot.vue.response.ResponseResult;
import cn.kgc.boot.vue.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 课工场
 * @date 2025/9/22
 * @description 控制层   接收http请求
 * /user/add
 * /user/delete
 * /user/one
 * @RequestMapping 请求映射
 */
@RestController   //  标识当前类为控制层   类中的返回数据全部是json格式数据
@RequestMapping("user")
@CrossOrigin   // 解决前后端分离项目中的跨域问题
public class UserController {

    /*
     *  根据java web开发规范   mvc结构   控制层  业务层
     * */
    @Resource
    private UserService userService;

    // 登录认证    /user/login
    @RequestMapping("login")
    public ResponseResult login(String username, String password) {
        System.out.println("username = " + username + ", password = " + password);
        // 根据用户名和密码查询数据库
        String md5Pwd = SecureUtil.md5(password);
        // 构建查询条件   where  username= ? and password= ?
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", username)
                .eq("password", md5Pwd);

        User one = userService.getOne(userQueryWrapper);

        ResponseResult responseResult = new ResponseResult();
        // 判定查询结果
        if (ObjectUtils.isNull(one)){
            responseResult.setCode(110);
            responseResult.setMessage("用户名或密码错误");
            return responseResult;
        }
        // 用户名和密码正确的
        responseResult.setCode(200);
        responseResult.setMessage("认证通过");

        return responseResult;
    }


    // 注册用户
    @RequestMapping("register")
    public ResponseResult register(String username, String password) {
        System.out.println("username = " + username + ", password = " + password);
        // 添加用户名 ，密码 到mysql数据库  password  123456
        String md5Pwd = SecureUtil.md5(password);

        User user = new User();
        user.setUsername(username);
        user.setPassword(md5Pwd);

        ResponseResult responseResult = new ResponseResult();
        try {
            userService.save(user);
            responseResult.setCode(200);
            responseResult.setMessage("注册成功，请登录");
        }catch (Exception e){
            e.printStackTrace();
            responseResult.setCode(500);
            responseResult.setMessage("注册失败,用户名重复");
        }
        return responseResult;
    }

}
